package com.cplsys.iacna.ui;

import java.awt.Component;

import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.cplsys.iacna.domain.Usuario;
import com.cplsys.iacna.services.UsuarioService;

/**
 * 
 * @author CPL
 */
@Repository
public class Logged extends JDialog {

	private static final long serialVersionUID = 1L;

	@Autowired
	private UsuarioService usuarioService;

	private String user;
	private String pass;
	private String nombre;

	public Logged() {
		initComponents();
		setLocationRelativeTo(null);
		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
		setModal(true);
	}

	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		labelUser = new javax.swing.JLabel();
		labelPassword = new javax.swing.JLabel();
		passwordField = new javax.swing.JPasswordField();
		buttonAcept = new javax.swing.JButton();
		buttonCancel = new javax.swing.JButton();
		userField = new javax.swing.JTextField();

		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
		addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowClosing(java.awt.event.WindowEvent evt) {
				formWindowClosing(evt);
			}
		});

		labelUser.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
		labelUser.setText("Usuario:");

		labelPassword.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
		labelPassword.setText("Contrasena:");

		passwordField.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				passwordFieldActionPerformed(evt);
			}
		});

		buttonAcept.setText("Aceptar");
		buttonAcept.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				buttonAceptActionPerformed(evt);
			}
		});
		buttonAcept.addKeyListener(new java.awt.event.KeyAdapter() {
			public void keyPressed(java.awt.event.KeyEvent evt) {
				buttonAceptKeyPressed(evt);
			}
		});

		buttonCancel.setText("Cancelar");
		buttonCancel.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				buttonCancelActionPerformed(evt);
			}
		});

		userField.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				userFieldActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.TRAILING)
												.addComponent(labelPassword)
												.addComponent(labelUser))
								.addGap(18, 18, 18)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.LEADING,
												false)
												.addGroup(
														layout.createSequentialGroup()
																.addComponent(
																		buttonAcept,
																		javax.swing.GroupLayout.PREFERRED_SIZE,
																		79,
																		javax.swing.GroupLayout.PREFERRED_SIZE)
																.addPreferredGap(
																		javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																.addComponent(
																		buttonCancel,
																		javax.swing.GroupLayout.DEFAULT_SIZE,
																		javax.swing.GroupLayout.DEFAULT_SIZE,
																		Short.MAX_VALUE))
												.addComponent(userField)
												.addComponent(
														passwordField,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														166,
														javax.swing.GroupLayout.PREFERRED_SIZE))
								.addGap(0, 29, Short.MAX_VALUE)));
		layout.setVerticalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(labelUser)
												.addComponent(
														userField,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE))
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(labelPassword)
												.addComponent(
														passwordField,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE))
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(buttonAcept)
												.addComponent(buttonCancel))
								.addContainerGap(
										javax.swing.GroupLayout.DEFAULT_SIZE,
										Short.MAX_VALUE)));

		pack();
	}// </editor-fold>

	private void buttonAceptActionPerformed(java.awt.event.ActionEvent evt) {
		performLogin();
	}

	private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {

		setUser("cancel");
		setPass("");
		dispose();
	}

	private void buttonAceptKeyPressed(java.awt.event.KeyEvent evt) {

	}

	private void performLogin() {
		if (userField.getText().isEmpty()
				|| passwordField.getPassword().length == 0) {
			JOptionPane.showMessageDialog(null,
					"POR FAVOR COMPLETE LA INFORMACION SOLICITADA", "",
					JOptionPane.WARNING_MESSAGE);
		} else {
			Usuario usuario = usuarioService.getUsuario(userField.getText(), passwordField.getText());
			
			if (usuario != null) {
				setUser(usuario.getIdUsuario().toString());
				setNombre(usuario.getApellidoPaterno().toString()+ " "+ usuario.getApellidoMaterno()+" "+ usuario.getNombre());
				dispose();
				Component componentes[] = getContentPane().getComponents(); 
                //System.out.println(componentes[].length);
                for(int i=0; i<componentes.length;i++)
                {
                    String clase = componentes[i].getClass().getName();

                    if(clase.equals("javax.swing.JTextField"))
                    {
                        JTextField tmp = (JTextField)componentes[i];
                        tmp.setText("");
                    }

                    if(clase.equals("javax.swing.JPasswordField"))
                    {
                        JPasswordField tmp = (JPasswordField)componentes[i];
                        tmp.setText("");
                    }

                    if(clase.equals("javax.swing.JComboBox"))
                    {
                        JComboBox tmp = (JComboBox)componentes[i];
                        tmp.setSelectedIndex(0);
                    }

                    if(clase.equals("javax.swing.JCheckBox"))
                    {
                        JCheckBox tmp = (JCheckBox)componentes[i];
                        tmp.setSelected(false);
                    }
                    if(clase.equals("javax.swing.JTable"))
                    {
                        JTable tmp = (JTable)componentes[i];
                        tmp.setModel(new DefaultTableModel());
                    } 
                }
			}
			else JOptionPane.showMessageDialog(null, "Usuario "+userField.getText()+" No existe");
			
		}
	}

	private void formWindowClosing(java.awt.event.WindowEvent evt) {

		setUser("cancel");
		setPass("");
		dispose();
	}

	private void userFieldActionPerformed(java.awt.event.ActionEvent evt) {
		performLogin();
	}

	private void passwordFieldActionPerformed(java.awt.event.ActionEvent evt) {
		performLogin();
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPass() {
		return pass;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}
	public String getNombre() {
		return nombre;
	}

	public void setNombre(String nombre) {
		this.nombre = nombre;
	}

	// Variables declaration - do not modify
	private javax.swing.JButton buttonAcept;
	private javax.swing.JButton buttonCancel;
	private javax.swing.JLabel labelPassword;
	private javax.swing.JLabel labelUser;
	private javax.swing.JPasswordField passwordField;
	private javax.swing.JTextField userField;
	// End of variables declaration
}
